from python.common.ws import WsClient
from python.common.config import WS_HOOK_URL, UA
from python.boss.create_url import jobListUrl
from python.db.storage import Table
import time
import requests

key_city = 'city'
key_position = 'position'
key_page = 'page'
key_max_page = 'max_page'

tb_jobs = Table('jobs')


def map_data(jobs):
    for job in jobs:
        if 'jobLabels' in job:
            job['jobLabels'] = ','.join(job['jobLabels'])
        if 'skills' in job:
            job['skills'] = ','.join(job['skills'])
        if 'iconFlagList' in job:
            job['iconFlagList'] = ','.join(job['iconFlagList'])
        if 'welfareList' in job:
            job['welfareList'] = ','.join(job['welfareList'])
        job['detailState'] = 0
        job['companyState'] = 0
    return jobs


def makeRequest(url, cookie):
    headers = {
        'Cookie': cookie,
        'User-Agent': UA
    }
    return requests.get(url, headers=headers)


def fetch_data(cookie, ctx):
    page = ctx.args[key_page]
    city = ctx.args[key_city]
    position = ctx.args[key_position]
    url = jobListUrl(page, city, position)
    response = makeRequest(url, cookie)
    jobs = response.json().get('zpData', {}).get('jobList', [])
    if len(jobs) > 0:
        print(f"保存第{page}页数据", jobs)
        jobs = map_data(jobs)
        tb_jobs.save(jobs)
        ctx.args[key_page] = page + 1
        return True
    else:
        print(f"请求到第{page}页重新生成cookie")
        ctx.post({'target': 'B'})
        return False


def on_msg(msg, ctx):
    cookie = msg.get('data', '')
    while ctx.args[key_page] <= ctx.args[key_max_page]:
        state = fetch_data(cookie, ctx)
        if not state:
            break
        time.sleep(5)


def setup(page, max_page, city, position):
    ws = WsClient(WS_HOOK_URL)
    ws.param(key_page, page)
    ws.param(key_max_page, max_page)
    ws.param(key_city, city)
    ws.param(key_position, position)
    ws.receive(on_msg)

